from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import db
from app.models.user import User
from sqlalchemy import text
from datetime import datetime
import json

form_templates_bp = Blueprint('form_templates', __name__)

@form_templates_bp.route('/<form_type>', methods=['GET'])
def get_form_template(form_type):
    """获取指定类型的表单模板"""
    try:
        query = text("""
            SELECT id, form_type, field_name, field_label, field_type, 
                   field_options, validation_rules, default_value, 
                   placeholder, help_text, sort_order, is_required, is_active
            FROM form_field_templates 
            WHERE form_type = :form_type AND is_active = 1
            ORDER BY sort_order ASC, id ASC
        """)
        
        result = db.session.execute(query, {'form_type': form_type})
        fields = []
        
        for row in result:
            # 解析JSON字段
            field_options = None
            validation_rules = None
            
            try:
                if row.field_options:
                    field_options = json.loads(row.field_options)
            except (json.JSONDecodeError, TypeError):
                field_options = None
            
            try:
                if row.validation_rules:
                    validation_rules = json.loads(row.validation_rules)
            except (json.JSONDecodeError, TypeError):
                validation_rules = None
            
            fields.append({
                'id': row.id,
                'form_type': row.form_type,
                'field_name': row.field_name,
                'field_label': row.field_label,
                'field_type': row.field_type,
                'field_options': field_options,
                'validation_rules': validation_rules,
                'default_value': row.default_value,
                'placeholder': row.placeholder,
                'help_text': row.help_text,
                'sort_order': row.sort_order,
                'is_required': bool(row.is_required),
                'is_active': bool(row.is_active)
            })
        
        return jsonify({
            'form_type': form_type,
            'fields': fields,
            'total': len(fields)
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/types', methods=['GET'])
def get_form_types():
    """获取所有表单类型"""
    try:
        query = text("""
            SELECT DISTINCT form_type, COUNT(*) as field_count
            FROM form_field_templates 
            WHERE is_active = 1
            GROUP BY form_type
            ORDER BY form_type
        """)
        
        result = db.session.execute(query)
        types = []
        
        for row in result:
            types.append({
                'form_type': row.form_type,
                'field_count': row.field_count
            })
        
        return jsonify({'types': types}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/field-types', methods=['GET'])
def get_field_types():
    """获取所有字段类型"""
    try:
        # 定义系统支持的字段类型
        field_types = [
            {'value': 'text', 'label': '文本输入'},
            {'value': 'textarea', 'label': '多行文本'},
            {'value': 'number', 'label': '数字'},
            {'value': 'email', 'label': '邮箱'},
            {'value': 'phone', 'label': '电话'},
            {'value': 'date', 'label': '日期'},
            {'value': 'datetime', 'label': '日期时间'},
            {'value': 'time', 'label': '时间'},
            {'value': 'select', 'label': '下拉选择'},
            {'value': 'radio', 'label': '单选按钮'},
            {'value': 'checkbox', 'label': '复选框'},
            {'value': 'file', 'label': '文件上传'},
            {'value': 'image', 'label': '图片上传'},
            {'value': 'url', 'label': '网址'},
            {'value': 'password', 'label': '密码'},
            {'value': 'hidden', 'label': '隐藏字段'}
        ]
        
        return jsonify({'field_types': field_types}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/fields', methods=['POST'])
def create_field():
    """创建字段模板"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['field_name', 'field_label', 'field_type']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'error': f'{field} 不能为空'}), 400
        
        # 插入数据库
        insert_query = text("""
            INSERT INTO form_field_templates (
                form_type, field_name, field_label, field_type, field_options,
                validation_rules, default_value, placeholder, help_text,
                sort_order, is_required, is_active, created_at, updated_at
            ) VALUES (
                :form_type, :field_name, :field_label, :field_type, :field_options,
                :validation_rules, :default_value, :placeholder, :help_text,
                :sort_order, :is_required, :is_active, datetime('now'), datetime('now')
            )
        """)
        
        params = {
            'form_type': data.get('form_type', data.get('category', 'default')),
            'field_name': data.get('field_name'),
            'field_label': data.get('field_label'),
            'field_type': data.get('field_type'),
            'field_options': data.get('field_options', ''),
            'validation_rules': data.get('validation_rules', ''),
            'default_value': data.get('default_value', ''),
            'placeholder': data.get('placeholder', ''),
            'help_text': data.get('help_text', ''),
            'sort_order': data.get('sort_order', 0),
            'is_required': 1 if data.get('is_required', False) else 0,
            'is_active': 1 if data.get('is_active', True) else 0
        }
        
        result = db.session.execute(insert_query, params)
        db.session.commit()
        
        # 获取新创建的ID
        new_id = result.lastrowid
        
        return jsonify({
            'message': '字段模板创建成功',
            'id': new_id
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建失败: {str(e)}'}), 500

@form_templates_bp.route('/fields/<int:field_id>', methods=['PUT'])
def update_field(field_id):
    """更新字段模板"""
    try:
        data = request.get_json()
        
        # 检查字段是否存在
        check_query = text("SELECT id FROM form_field_templates WHERE id = :field_id")
        result = db.session.execute(check_query, {'field_id': field_id})
        field = result.fetchone()
        
        if not field:
            return jsonify({'error': '字段模板不存在'}), 404
        
        # 构建更新语句
        update_fields = []
        params = {'field_id': field_id}
        
        # 可更新的字段列表
        updatable_fields = {
            'form_type': 'form_type',
            'category': 'form_type',  # category映射到form_type
            'field_name': 'field_name',
            'field_label': 'field_label',
            'field_type': 'field_type',
            'field_options': 'field_options',
            'validation_rules': 'validation_rules',
            'default_value': 'default_value',
            'placeholder': 'placeholder',
            'help_text': 'help_text',
            'sort_order': 'sort_order',
            'is_required': 'is_required',
            'is_active': 'is_active'
        }
        
        for key, db_field in updatable_fields.items():
            if key in data:
                update_fields.append(f"{db_field} = :{db_field}")
                if key in ['is_required', 'is_active']:
                    params[db_field] = 1 if data[key] else 0
                else:
                    params[db_field] = data[key]
        
        if not update_fields:
            return jsonify({'error': '没有提供要更新的字段'}), 400
        
        # 添加更新时间
        update_fields.append("updated_at = datetime('now')")
        
        update_query = text(f"""
            UPDATE form_field_templates 
            SET {', '.join(update_fields)}
            WHERE id = :field_id
        """)
        
        db.session.execute(update_query, params)
        db.session.commit()
        
        return jsonify({
            'message': '字段模板更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新失败: {str(e)}'}), 500

@form_templates_bp.route('/fields/<int:field_id>', methods=['DELETE'])
def delete_field(field_id):
    """删除字段模板"""
    try:
        # 检查字段是否存在
        query = text("SELECT id FROM form_field_templates WHERE id = :field_id")
        result = db.session.execute(query, {'field_id': field_id})
        field = result.fetchone()
        
        if not field:
            return jsonify({'error': '字段模板不存在'}), 404
        
        # 删除字段模板
        delete_query = text("DELETE FROM form_field_templates WHERE id = :field_id")
        db.session.execute(delete_query, {'field_id': field_id})
        db.session.commit()
        
        return jsonify({
            'message': '字段模板删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'删除失败: {str(e)}'}), 500

@form_templates_bp.route('/preview', methods=['POST'])
def preview_field():
    """预览字段"""
    data = request.get_json()
    
    # 生成简单的HTML预览
    field_type = data.get('field_type', 'text')
    field_label = data.get('field_label', '字段')
    
    html_map = {
        'text': f'<input type="text" placeholder="{field_label}" />',
        'textarea': f'<textarea placeholder="{field_label}"></textarea>',
        'number': f'<input type="number" placeholder="{field_label}" />',
        'select': f'<select><option>{field_label}</option></select>',
        'radio': f'<input type="radio" name="{field_label}" /> {field_label}',
        'checkbox': f'<input type="checkbox" /> {field_label}',
        'file': f'<input type="file" />'
    }
    
    html = html_map.get(field_type, f'<input type="text" placeholder="{field_label}" />')
    
    return jsonify({
        'html': f'<div class="field-preview"><label>{field_label}</label>{html}</div>'
    })

@form_templates_bp.route('/validate', methods=['POST'])
def validate_field_config():
    """验证字段配置"""
    data = request.get_json()
    
    errors = []
    
    # 基本验证
    if not data.get('field_name'):
        errors.append('字段名称不能为空')
    if not data.get('field_label'):
        errors.append('字段标签不能为空')
    if not data.get('field_type'):
        errors.append('字段类型不能为空')
    
    return jsonify({
        'isValid': len(errors) == 0,
        'errors': errors
    })

@form_templates_bp.route('/fields/order', methods=['POST'])
def update_fields_order():
    """更新字段排序"""
    try:
        data = request.get_json()
        updates = data.get('updates', [])
        
        if not updates:
            return jsonify({'error': '没有提供排序更新数据'}), 400
        
        # 批量更新排序
        for update in updates:
            field_id = update.get('id')
            sort_order = update.get('sort_order')
            
            if field_id is None or sort_order is None:
                continue
                
            update_query = text("""
                UPDATE form_field_templates 
                SET sort_order = :sort_order, updated_at = datetime('now')
                WHERE id = :field_id
            """)
            
            db.session.execute(update_query, {
                'field_id': field_id,
                'sort_order': sort_order
            })
        
        db.session.commit()
        
        return jsonify({
            'message': '字段排序更新成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'排序更新失败: {str(e)}'}), 500

@form_templates_bp.route('/fields', methods=['GET'])
def get_all_fields():
    """获取所有字段模板"""
    try:
        # 获取查询参数
        category = request.args.get('category', '')
        field_type = request.args.get('field_type', '')
        is_active = request.args.get('is_active', '')
        
        # 构建查询条件
        conditions = []
        params = {}
        
        if category:
            conditions.append('form_type = :category')
            params['category'] = category
        
        if field_type:
            conditions.append('field_type = :field_type')
            params['field_type'] = field_type
        
        if is_active:
            conditions.append('is_active = :is_active')
            params['is_active'] = 1 if is_active.lower() == 'true' else 0
        
        where_clause = 'WHERE ' + ' AND '.join(conditions) if conditions else ''
        
        query = text(f"""
            SELECT id, form_type, field_name, field_label, field_type, 
                   field_options, validation_rules, default_value, 
                   placeholder, help_text, sort_order, is_required, is_active,
                   created_at, updated_at,
                   COALESCE(form_type, 'default') as category
            FROM form_field_templates 
            {where_clause}
            ORDER BY category, sort_order ASC, id ASC
        """)
        
        result = db.session.execute(query, params)
        fields = []
        
        for row in result:
            # 解析JSON字段
            field_options = None
            validation_rules = None
            
            try:
                if row.field_options:
                    field_options = json.loads(row.field_options)
            except (json.JSONDecodeError, TypeError):
                field_options = None
            
            try:
                if row.validation_rules:
                    validation_rules = json.loads(row.validation_rules)
            except (json.JSONDecodeError, TypeError):
                validation_rules = None
            
            fields.append({
                'id': row.id,
                'form_type': row.form_type,
                'field_name': row.field_name,
                'field_label': row.field_label,
                'field_type': row.field_type,
                'field_options': field_options,
                'validation_rules': validation_rules,
                'default_value': row.default_value,
                'placeholder': row.placeholder,
                'help_text': row.help_text,
                'sort_order': row.sort_order,
                'is_required': bool(row.is_required),
                'is_active': bool(row.is_active),
                'category': row.category or row.form_type or 'default',
                'created_at': row.created_at if isinstance(row.created_at, str) else (row.created_at.isoformat() if row.created_at else None),
                'updated_at': row.updated_at if isinstance(row.updated_at, str) else (row.updated_at.isoformat() if row.updated_at else None)
            })
        
        return jsonify(fields), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/manage', methods=['GET'])
@jwt_required()
def get_templates_manage():
    """获取表单模板管理列表（管理员用）"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        form_type = request.args.get('form_type', '')
        search = request.args.get('search', '')
        
        # 构建查询条件
        conditions = []
        params = {}
        
        if form_type:
            conditions.append('form_type = :form_type')
            params['form_type'] = form_type
        
        if search:
            conditions.append('(field_name LIKE :search OR field_label LIKE :search)')
            params['search'] = f'%{search}%'
        
        where_clause = 'WHERE ' + ' AND '.join(conditions) if conditions else ''
        
        # 查询总数
        count_query = text(f"""
            SELECT COUNT(*) as total
            FROM form_field_templates 
            {where_clause}
        """)
        
        total_result = db.session.execute(count_query, params)
        total = total_result.scalar()
        
        # 查询数据
        offset = (page - 1) * per_page
        data_query = text(f"""
            SELECT id, form_type, field_name, field_label, field_type, 
                   field_options, validation_rules, default_value, 
                   placeholder, help_text, sort_order, is_required, 
                   is_active, created_at, updated_at
            FROM form_field_templates 
            {where_clause}
            ORDER BY form_type, sort_order ASC, id ASC
            LIMIT :per_page OFFSET :offset
        """)
        
        params.update({'per_page': per_page, 'offset': offset})
        result = db.session.execute(data_query, params)
        
        templates = []
        for row in result:
            # 解析JSON字段
            field_options = None
            validation_rules = None
            
            try:
                if row.field_options:
                    field_options = json.loads(row.field_options)
            except (json.JSONDecodeError, TypeError):
                field_options = None
            
            try:
                if row.validation_rules:
                    validation_rules = json.loads(row.validation_rules)
            except (json.JSONDecodeError, TypeError):
                validation_rules = None
            
            templates.append({
                'id': row.id,
                'form_type': row.form_type,
                'field_name': row.field_name,
                'field_label': row.field_label,
                'field_type': row.field_type,
                'field_options': field_options,
                'validation_rules': validation_rules,
                'default_value': row.default_value,
                'placeholder': row.placeholder,
                'help_text': row.help_text,
                'sort_order': row.sort_order,
                'is_required': bool(row.is_required),
                'is_active': bool(row.is_active),
                'created_at': row.created_at.isoformat() if row.created_at else None,
                'updated_at': row.updated_at.isoformat() if row.updated_at else None
            })
        
        return jsonify({
            'templates': templates,
            'total': total,
            'page': page,
            'per_page': per_page,
            'pages': (total + per_page - 1) // per_page
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('', methods=['POST'])
@jwt_required()
def create_template():
    """创建表单字段模板"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['form_type', 'field_name', 'field_label', 'field_type']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'error': f'{field} 不能为空'}), 400
        
        # 检查字段名是否在同一表单类型中重复
        check_query = text("""
            SELECT COUNT(*) as count
            FROM form_field_templates 
            WHERE form_type = :form_type AND field_name = :field_name
        """)
        
        result = db.session.execute(check_query, {
            'form_type': data['form_type'],
            'field_name': data['field_name']
        })
        
        if result.scalar() > 0:
            return jsonify({'error': '该表单类型中已存在相同的字段名'}), 400
        
        # 处理JSON字段
        field_options_json = None
        validation_rules_json = None
        
        if data.get('field_options'):
            try:
                field_options_json = json.dumps(data['field_options'], ensure_ascii=False)
            except (TypeError, ValueError) as e:
                return jsonify({'error': f'字段选项格式错误: {str(e)}'}), 400
        
        if data.get('validation_rules'):
            try:
                validation_rules_json = json.dumps(data['validation_rules'], ensure_ascii=False)
            except (TypeError, ValueError) as e:
                return jsonify({'error': f'验证规则格式错误: {str(e)}'}), 400
        
        # 插入新模板
        insert_query = text("""
            INSERT INTO form_field_templates 
            (form_type, field_name, field_label, field_type, field_options, 
             validation_rules, default_value, placeholder, help_text, 
             sort_order, is_required, is_active, created_at, updated_at)
            VALUES (:form_type, :field_name, :field_label, :field_type, :field_options,
                    :validation_rules, :default_value, :placeholder, :help_text,
                    :sort_order, :is_required, :is_active, :created_at, :updated_at)
        """)
        
        now = datetime.now()
        db.session.execute(insert_query, {
            'form_type': data['form_type'],
            'field_name': data['field_name'],
            'field_label': data['field_label'],
            'field_type': data['field_type'],
            'field_options': field_options_json,
            'validation_rules': validation_rules_json,
            'default_value': data.get('default_value'),
            'placeholder': data.get('placeholder'),
            'help_text': data.get('help_text'),
            'sort_order': data.get('sort_order', 0),
            'is_required': data.get('is_required', False),
            'is_active': data.get('is_active', True),
            'created_at': now,
            'updated_at': now
        })
        
        db.session.commit()
        
        return jsonify({'message': '表单模板创建成功'}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/<int:template_id>', methods=['PUT'])
@jwt_required()
def update_template(template_id):
    """更新表单字段模板"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        
        # 检查模板是否存在
        check_query = text("""
            SELECT id FROM form_field_templates WHERE id = :id
        """)
        
        result = db.session.execute(check_query, {'id': template_id})
        if not result.fetchone():
            return jsonify({'error': '模板不存在'}), 404
        
        # 构建更新字段
        update_fields = []
        params = {'id': template_id, 'updated_at': datetime.now()}
        
        # 处理普通字段
        allowed_fields = ['field_label', 'field_type', 'default_value', 
                         'placeholder', 'help_text', 'sort_order', 
                         'is_required', 'is_active']
        
        for field in allowed_fields:
            if field in data:
                update_fields.append(f'{field} = :{field}')
                params[field] = data[field]
        
        # 处理JSON字段
        if 'field_options' in data:
            try:
                field_options_json = json.dumps(data['field_options'], ensure_ascii=False) if data['field_options'] else None
                update_fields.append('field_options = :field_options')
                params['field_options'] = field_options_json
            except (TypeError, ValueError) as e:
                return jsonify({'error': f'字段选项格式错误: {str(e)}'}), 400
        
        if 'validation_rules' in data:
            try:
                validation_rules_json = json.dumps(data['validation_rules'], ensure_ascii=False) if data['validation_rules'] else None
                update_fields.append('validation_rules = :validation_rules')
                params['validation_rules'] = validation_rules_json
            except (TypeError, ValueError) as e:
                return jsonify({'error': f'验证规则格式错误: {str(e)}'}), 400
        
        if not update_fields:
            return jsonify({'error': '没有可更新的字段'}), 400
        
        update_fields.append('updated_at = :updated_at')
        
        # 执行更新
        update_query = text(f"""
            UPDATE form_field_templates 
            SET {', '.join(update_fields)}
            WHERE id = :id
        """)
        
        db.session.execute(update_query, params)
        db.session.commit()
        
        return jsonify({'message': '模板更新成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/<int:template_id>', methods=['DELETE'])
@jwt_required()
def delete_template(template_id):
    """删除表单字段模板"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        # 检查模板是否存在
        check_query = text("""
            SELECT id FROM form_field_templates WHERE id = :id
        """)
        
        result = db.session.execute(check_query, {'id': template_id})
        if not result.fetchone():
            return jsonify({'error': '模板不存在'}), 404
        
        # 删除模板
        delete_query = text("""
            DELETE FROM form_field_templates WHERE id = :id
        """)
        
        db.session.execute(delete_query, {'id': template_id})
        db.session.commit()
        
        return jsonify({'message': '模板删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/batch', methods=['POST'])
@jwt_required()
def batch_update_templates():
    """批量更新表单模板"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        ids = data.get('ids', [])
        action = data.get('action')  # 'activate', 'deactivate', 'delete'
        
        if not ids or not action:
            return jsonify({'error': '参数不完整'}), 400
        
        if action == 'activate':
            query = text("""
                UPDATE form_field_templates 
                SET is_active = 1, updated_at = :updated_at
                WHERE id IN :ids
            """)
        elif action == 'deactivate':
            query = text("""
                UPDATE form_field_templates 
                SET is_active = 0, updated_at = :updated_at
                WHERE id IN :ids
            """)
        elif action == 'delete':
            if user.role != 'admin':
                return jsonify({'error': '只有管理员可以删除模板'}), 403
            query = text("""
                DELETE FROM form_field_templates 
                WHERE id IN :ids
            """)
        else:
            return jsonify({'error': '无效的操作类型'}), 400
        
        # 将列表转换为元组以用于SQL IN子句
        ids_tuple = tuple(ids)
        params = {'ids': ids_tuple}
        
        if action != 'delete':
            params['updated_at'] = datetime.now()
        
        db.session.execute(query, params)
        db.session.commit()
        
        return jsonify({'message': f'批量{action}操作成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@form_templates_bp.route('/copy', methods=['POST'])
@jwt_required()
def copy_template():
    """复制表单模板"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        source_id = data.get('source_id')
        new_form_type = data.get('new_form_type')
        new_field_name = data.get('new_field_name')
        
        if not all([source_id, new_form_type, new_field_name]):
            return jsonify({'error': '参数不完整'}), 400
        
        # 获取源模板
        source_query = text("""
            SELECT form_type, field_name, field_label, field_type, field_options, 
                   validation_rules, default_value, placeholder, help_text, 
                   sort_order, is_required, is_active
            FROM form_field_templates 
            WHERE id = :id
        """)
        
        result = db.session.execute(source_query, {'id': source_id})
        source = result.fetchone()
        
        if not source:
            return jsonify({'error': '源模板不存在'}), 404
        
        # 检查新字段名是否重复
        check_query = text("""
            SELECT COUNT(*) as count
            FROM form_field_templates 
            WHERE form_type = :form_type AND field_name = :field_name
        """)
        
        result = db.session.execute(check_query, {
            'form_type': new_form_type,
            'field_name': new_field_name
        })
        
        if result.scalar() > 0:
            return jsonify({'error': '目标表单类型中已存在相同的字段名'}), 400
        
        # 复制模板
        insert_query = text("""
            INSERT INTO form_field_templates 
            (form_type, field_name, field_label, field_type, field_options, 
             validation_rules, default_value, placeholder, help_text, 
             sort_order, is_required, is_active, created_at, updated_at)
            VALUES (:form_type, :field_name, :field_label, :field_type, :field_options,
                    :validation_rules, :default_value, :placeholder, :help_text,
                    :sort_order, :is_required, :is_active, :created_at, :updated_at)
        """)
        
        now = datetime.now()
        db.session.execute(insert_query, {
            'form_type': new_form_type,
            'field_name': new_field_name,
            'field_label': source.field_label,
            'field_type': source.field_type,
            'field_options': source.field_options,
            'validation_rules': source.validation_rules,
            'default_value': source.default_value,
            'placeholder': source.placeholder,
            'help_text': source.help_text,
            'sort_order': source.sort_order,
            'is_required': source.is_required,
            'is_active': source.is_active,
            'created_at': now,
            'updated_at': now
        })
        
        db.session.commit()
        
        return jsonify({'message': '模板复制成功'}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500